package com.qianfeng.user;

import com.qianfeng.user.dao.entity.UserEntity;
import com.qianfeng.user.dao.mapper.UserMapper;
import com.qianfeng.user.dto.UserRequest;
import com.qianfeng.user.dto.UserResponse;
import com.qianfeng.user.util.JWTTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.joda.time.DateTime;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 用户业务实现类
 * @author  Martin
 */
@Service("userServiceImpl")
public class UserServiceImpl implements IUserService{

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录方法实现
     * @param  request 请求参数
     * @return 登录结果
     */
    public UserResponse login(UserRequest request) {

        //非空校验
        UserResponse ur = verification(request);
        if(null != ur){
            return ur;
        }

        UserEntity ue = new UserEntity();
        ue.setUserName(request.getUserName());
        ue.setUserPass(request.getUserPass());

        //执行登录
        UserEntity user = userMapper.login(ue);

        ur = new UserResponse();

        if(null == user){ //登录失败
            ur.setCode(ErrorCode.CODE_LOGIN_FAIL);
            ur.setMsg(ErrorCode.MSG_LOGIN_FAIL);
            return ur;
        }

        //获取token
        Map<String,Object> map=new HashMap<>();
        map.put("uid",user.getUserID());
        map.put("exp",DateTime.now().plusSeconds(30).toDate().getTime()/1000); //设置过期时间 当前时间的基础上加上30s

        String token = JWTTokenUtil.generatorToken(map); //通过封装的算法来获取token
        ur.setToken(token);


        ur.setUid(user.getUserID());//将一些用户信息返回,可以封装一个通用类

        return ur;
    }

    //非空校验
    private UserResponse verification(UserRequest request){
        UserResponse ur = null;

        //请求为空
        if(null == request){
            ur = new UserResponse();
            ur.setCode(ErrorCode.CODE_ERROR_SYSTEM);
            ur.setMsg(ErrorCode.MSG_ERROR_SYSTEM);
            return ur;
        }

        //用户名为空
        if(StringUtils.isEmpty(request.getUserName())){
            ur = new UserResponse();
            ur.setCode(ErrorCode.CODE_USER_EMPTY);
            ur.setMsg(ErrorCode.MSG_USER_EMPTY);
            return ur;
        }

        //密码为空
        if(StringUtils.isEmpty(request.getUserPass())){
            ur = new UserResponse();
            ur.setCode(ErrorCode.CODE_PASS_EMPTY);
            ur.setMsg(ErrorCode.MSG_PASS_EMPTY);
            return ur;
        }

        return ur;
    }
}
